package com.bian.springboot04thymeleaf.config;

import com.bian.springboot04thymeleaf.listener.MyLisenter;
import com.bian.springboot04thymeleaf.servlet.MyServlet;
import filter.MyFilter;
import groovy.util.logging.Slf4j;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.EventListener;
import java.util.Locale;

/**
 * @author bianpengfei
 * @create 2019-01-29 18:50
 **/

// 使用 WebMvcConfigurerAdapter来扩展SpringMvc的功能
@Slf4j
@Configuration
public class MySpringConfig {

    /**
     * 注册三大组件
     * */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new MyServlet(), "/myServlet");
    }

    /**
     * 创建嵌入式servlet定制容器
     * */
    @Bean
    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            // 定制嵌入式的Servlet容器相关规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.setPort(8088);
            }
        };
    }

    /**
     * 注册 过滤器
     * */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return filterRegistrationBean;
    }

    /**
     * 注册 Listen监听器
     * */
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean() {
        ServletListenerRegistrationBean<MyLisenter> listener = new ServletListenerRegistrationBean<>();
        listener.setListener(new MyLisenter());
        return listener;
    }

    @Bean
    public WebMvcConfigurerAdapter adapter() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            // 注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                // 静态资源拦截 css js
                // SpringBoot已经为我们做好静态资源映射
                registry.addInterceptor(new HandlerInterceptor() {
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                        Object username = request.getSession().getAttribute("username");
                        if (username == null ) {
                            // 未登录，返回登录界面
                            request.setAttribute("msg", "没有权限，请登陆");
                            request.getRequestDispatcher("/index.html").forward(request, response);
                            return false;
                        }
                        // 已登录，放行请求
                        return true;
                    }

                    @Override
                    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

                    }

                    @Override
                    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

                    }
                }).addPathPatterns("/**").excludePathPatterns("/", "/index.html", "/user/login");
            }
        };
    }

    // 添加国际化资源解析
    @Bean
    public LocaleResolver localeResolver () {
        return new LocaleResolver() {
            @Override
            public Locale resolveLocale(HttpServletRequest request) {
                String localeStr = request.getParameter("locale");
                Locale locale = Locale.getDefault();
                if (!StringUtils.isEmpty(localeStr)) {
                    String[] split = localeStr.split("_");
                    locale = new Locale(split[0], split[1]);
                }
                return locale;
            }

            @Override
            public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

            }
        };
    }




    /**
     * 拦截器
     * */
    public HandlerInterceptor handlerInterceptor () {
        return new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                Object username = request.getSession().getAttribute("username");
                if (username == null ) {
                    // 未登录，返回登录界面
                    request.setAttribute("msg", "没有权限，请登陆");
                    request.getRequestDispatcher("/index.html").forward(request, response);
                    return false;
                }
                // 已登录，放行请求
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

            }
        };
    }


}
